#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
#include "createnewtorrent.h"
#include <QCryptographicHash>
#include <QDateTime>

CreateNewTorrent::CreateNewTorrent(QWidget *parent)
	: QDialog(parent)
{
	setupUi(this);
	setFixedSize(size().width(),size().height()); //365,472

	//Настройки, чтение
	QSettings settings(QSettings::IniFormat,QSettings::UserScope,"LinTorrent", "LinTorrent");
	settings.setIniCodec("UTF-8");
	settings.beginGroup("CreateNewTorrentDialog");
	textTrackers->setPlainText(settings.value("trackers").toString());
	textWeb->setPlainText(settings.value("webSeeds").toString());
	editComment->setText(settings.value("comment").toString());
	checkStartSeeding->setChecked(settings.value("startSeeding").toBool());
	checkPreserveOrder->setChecked(settings.value("preserveOrder").toBool());
	checkPrivate->setChecked(settings.value("private").toBool());
	settings.endGroup();
	//Настройки, чтение

	connect(buttonAddFile, SIGNAL(clicked()), this, SLOT(clickAddFile()));
	connect(buttonAddDirectory, SIGNAL(clicked()), this, SLOT(clickAddDirectory()));
	connect(buttonCreateAndSave, SIGNAL(clicked()), this, SLOT(clickCreateAndSave()));
	connect(buttonClose, SIGNAL(clicked()), this, SLOT(clickClose()));
}

//Слоты
void CreateNewTorrent::clickAddFile()
{
	QString fileName = QFileDialog::getOpenFileName(this,tr("Select a file"),comboPath->currentText(),tr("All files (*)"));
	if (!fileName.isEmpty()) {
		if (comboPath->findText(fileName) == -1) {
			comboPath->addItem(fileName);
		}
		comboPath->setCurrentIndex(comboPath->findText(fileName));
		choosedDir=false;
		labelSkipFiles->setEnabled(choosedDir);
		editSkipFiles->setEnabled(choosedDir);
	}
}
void CreateNewTorrent::clickAddDirectory()
{
	QString dirName = QFileDialog::getExistingDirectory(this,tr("Select a folder"),comboPath->currentText(),QFileDialog::ShowDirsOnly);
	if (!dirName.isEmpty()) {
		if (comboPath->findText(dirName) == -1) {
			comboPath->addItem(dirName);
		}
		comboPath->setCurrentIndex(comboPath->findText(dirName));
		choosedDir=true;
		labelSkipFiles->setEnabled(choosedDir);
		editSkipFiles->setEnabled(choosedDir);
	}

}
void CreateNewTorrent::clickCreateAndSave()
{
	uint startTime=QDateTime::currentDateTime().toTime_t();
	if (comboPath->currentText().length()==0) {
		QMessageBox::warning(this, "LinTorrent", tr("Please enter the name of a file or directory."));
		return;
	}
	QStringList trackerArray;
	trackerArray = textTrackers->toPlainText().split("\n");
	if (textTrackers->toPlainText().length() == 0) {
		int r=QMessageBox::question(this,"LinTorrent",tr("Please enter a valid tracker URL.\n"
														 "Do you want to continue without "
														 "having any trackers?"),
									QMessageBox::Yes | QMessageBox::Default,
									QMessageBox::No | QMessageBox::Escape);
		if (r == QMessageBox::No) return;
	}
	for (int i=0; i<trackerArray.size(); ++i) {
		if (trackerArray[i].length()==0) {
			trackerArray.takeAt(i);
			--i;
		}else
		if (trackerArray[i].left(7) != "http://" && trackerArray[i].left(8) != "https://") {
			int r=QMessageBox::question(this,"LinTorrent",tr("Tracker URL '%1' is invalid.\n"
															 "Do you want to continue?").arg(trackerArray[i]),
										   QMessageBox::Yes | QMessageBox::Default,
										   QMessageBox::No | QMessageBox::Escape);
			if (r == QMessageBox::No) return;
		}
	}
	QFile file(comboPath->currentText());
	if (!file.open(QIODevice::ReadOnly)) {
		QMessageBox::warning(this, "LinTorrent", tr("The file or directory '%1' cannot be found."
													"Please enter a different filename."
													"Note that you can't share the root of a drive.").arg(comboPath->currentText()));
		return;
	}

	//Сохранение настроек
	QSettings settings(QSettings::IniFormat,QSettings::UserScope,"LinTorrent", "LinTorrent");
	settings.setIniCodec("UTF-8");
	settings.beginGroup("CreateNewTorrentDialog");
	settings.setValue("trackers", textTrackers->toPlainText());
	settings.setValue("webSeeds", textWeb->toPlainText());
	settings.setValue("comment", editComment->text());
	settings.setValue("startSeeding", checkStartSeeding->isChecked());
	settings.setValue("preserveOrder", checkPreserveOrder->isChecked());
	settings.setValue("private", checkPrivate->isChecked());
	settings.endGroup();
	//Сохранение настроек

	QByteArray torrent="d";
	//QString tmp;
	if (trackerArray.size()>0) {
		//tmp=QString("%1:").arg(trackerArray[0].length());
		torrent.append(QString("8:announce%1:%2").arg(trackerArray[0].length()).arg(trackerArray[0]));
		if (trackerArray.size()>1) {
			torrent.append("13:announce-listl");
			for (int i=0; i<trackerArray.size(); ++i) {
				//tmp=QString("l%1:").arg(trackerArray[i].length());
				torrent.append(QString("l%1:%2e").arg(trackerArray[i].length()).arg(trackerArray[i]));
			}
			torrent.append("e");
		}
	}
	if (editComment->text().length()>0) {
		//tmp=QString("%1:").arg(editComment->text().toLocal8Bit().size());
		torrent.append(QString("7:comment%1:%2").arg(editComment->text().toLocal8Bit().length()).arg(editComment->text()));
	}
	torrent.append("10:created by15:LinTorrent/0000");
	torrent.append(QString("13:creation datei%1e").arg(QDateTime::currentDateTime().toTime_t()));
	//tmp=QString("%1").arg(QDateTime::currentDateTime().toTime_t());
	//torrent.append(tmp+"e");
	torrent.append("8:encoding5:UTF-8");
	torrent.append("4:infod");
	qint64 fSize=file.size();
	//tmp=QString("%1").arg(fSize);
	torrent.append(QString("6:lengthi%1e").arg(fSize));
	//QString fileName = QFileInfo(file).fileName();
	//tmp=QString("%1:").arg(fileName.toLocal8Bit().length());
	torrent.append(QString("4:name%1:%2").arg(QFileInfo(file).fileName().toLocal8Bit().length()).arg(QFileInfo(file).fileName()));
	qint64 pieceSize=0;
	qint64 gB=1073741824;
	switch (comboPieceSize->currentIndex()) {
		case 0: { //Auto
				if (fSize<=33554432)		pieceSize=32768;	//32 kB
				else if (fSize<=67108864)	pieceSize=65536;	//64 kB
				else if (fSize<=134217728)	pieceSize=131072;	//128 kB
				else if (fSize<=268435456)	pieceSize=262144;	//256 kB
				else if (fSize<=536870912)	pieceSize=524288;	//512 kB
				else if (fSize<=gB)		pieceSize=1048576;	//1 mB
				else if (fSize<=(2*gB)) pieceSize=2097152;	//2 mB
				else if (fSize<=(4*gB)) pieceSize=4194304;	//4mB
				break;
			}
		case 1: pieceSize=32768; break;
		case 2: pieceSize=65536; break;
		case 3: pieceSize=131072; break;
		case 4: pieceSize=262144; break;
		case 5: pieceSize=524288; break;
		case 6: pieceSize=1048576; break;
		case 7: pieceSize=2097152; break;
		case 8: pieceSize=4194304; break;
		default: ;
	}
	//tmp=QString("%1").arg(pieceSize);
	torrent.append(QString("12:piece lengthi%1e").arg(pieceSize));
	QByteArray hashes;
	QByteArray piece;
	qint64 readed=0;
	//QCryptographicHash *hash=new QCryptographicHash(QCryptographicHash::Sha1);
	while (!file.atEnd()){
		piece=file.read(pieceSize);
		readed+=piece.length();
		progressBar->setValue((readed*100)/fSize);
		//hash->reset();
		//hash->addData(piece);
		//hashes.append(hash->result());
		hashes.append(QCryptographicHash::hash(piece,QCryptographicHash::Sha1));
	}
	file.close();
	//tmp=QString("%1:").arg(hashes.length());
	torrent.append(QString("6:pieces%1:").arg(hashes.length()));
	torrent.append(hashes);
	if (checkPrivate->isChecked()) torrent.append("7:privatei1e");
	torrent.append("ee");
	uint endTime=QDateTime::currentDateTime().toTime_t();
	//tmp=QString("%1").arg(endTime-startTime);
	QMessageBox::information(this,"timer",tr("Secs: %1").arg(endTime-startTime));
	QString fileName=QFileDialog::getSaveFileName(this,tr("Select where to save the .torrent"),
								 comboPath->currentText()+".torrent",
								 tr("Torrent files (*.torrent);;All files (*)"));
	if (!fileName.isEmpty()) {
		file.setFileName(fileName);
		if (!file.open(QIODevice::WriteOnly)) {
			QMessageBox::warning(this, "LinTorrent", file.errorString());
			return;
		}
		if (!file.write(torrent)) QMessageBox::warning(this, "LinTorrent", file.errorString());
		file.close();
	}
	progressBar->setValue(0);

	//QMessageBox::information(this,"Sha1",QCryptographicHash::hash(all,QCryptographicHash::Sha1).toHex().toUpper());
}
void CreateNewTorrent::clickClose()
{
	close();
}

void CreateNewTorrent::changeEvent(QEvent *e)
{
	QDialog::changeEvent(e);
	switch (e->type()) {
	case QEvent::LanguageChange:
		retranslateUi(this);
		break;
	default:
		break;
	}
}
